<template>
	<div class='container'>
		<div class='login-box'>
			<h3>{{ title }}</h3>
			<el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
				:size="formSize" status-icon :label-width='auto'>
				<el-form-item label="" prop="username">
					<el-input v-model="ruleForm.username" :prefix-icon="User" input-style='' />
				</el-form-item>
				<el-form-item label="" prop="password">
					<el-input v-model="ruleForm.password" type="password" :prefix-icon="Lock" show-password />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="submitForm(ruleFormRef)">
						登录
					</el-button>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>

<script setup >
import { reactive, ref, getCurrentInstance, onMounted, watch } from 'vue'
import { useUserStore } from '@/stores/modules/user'
import { useRoute, useRouter } from 'vue-router'
// 当前页的实例使用
const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
import { User, Lock, Unlock } from '@element-plus/icons-vue'
import { login } from '@/api/user';
const title = import.meta.env.VITE_APP_TITLE
const formSize = ref('default')
const ruleFormRef = ref()
const store = useUserStore()
const ruleForm = reactive({
	username: 'admin',
	password: '111111'
})

const rules = reactive({
	username: [
		{ required: true, message: '请输入用户名', trigger: 'blur' },
		{ min: 3, max: 8, message: '长度3到8位', trigger: 'blur' },
	],
	password: [
		{ required: true, message: '请输入密码', trigger: 'blur' },
		{ min: 3, max: 8, message: '长度3到8位', trigger: 'blur' },
	],
})

const submitForm = async (formEl) => {
	if (!formEl) return
	await formEl.validate((valid, fields) => {
		if (valid) {
			login({ username: ruleForm.username, password: ruleForm.password })
				.then((resp) => {
					if (resp.code === 200) {
						// Element-plus全局的$message使用
						proxy.$message.success('登录成功!')
						// 存储token
						store.setUserToken(resp.data.tokenValue)
						// 跳转到首页
						router.push('/')
					} else {
						proxy.$message({ type: 'error', message: resp.msg })
					}
				}, (error) => {
					proxy.$message.error(error)
				})
		} else {
			console.log('error submit!', fields)
		}
	})
}
</script>

<style scoped lang="scss">
:deep(.el-form-item__content) {
	margin-left: 0 !important;
}

:deep(.el-button) {
	width: 100%;
}

.el-form-item--feedback {
	.el-input__validateIcon {
		display: none;
	}
}

.container {
	width: 100vw;
	height: 100vh;
	display: flex;
	background: #3B5998;
	justify-content: center;
	align-items: center;

	.login-box {
		width: 300px;
		height: 200px;
		background: #fff;
		border-radius: 10px;
		padding: 10px 20px;
		text-align: center;
	}
}
</style>